package com.zaozhuang.robot.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageDownloader {

    // 弱引用防止内存泄漏
    private WeakReference<Context> weakContext;
    private WeakReference<ImageView> weakImageView;
    private DownloadCallback callback;

    public interface DownloadCallback {
        void onSuccess(Bitmap bitmap);
        void onFailure(String error);
    }

    public ImageDownloader(Context context, ImageView imageView) {
        this.weakContext = new WeakReference<>(context);
        this.weakImageView = new WeakReference<>(imageView);
    }

    public ImageDownloader(Context context, DownloadCallback callback) {
        this.weakContext = new WeakReference<>(context);
        this.callback = callback;
    }

    public void execute(String imageUrl) {
        new DownloadTask().execute(imageUrl);
    }

    private class DownloadTask extends AsyncTask<String, Void, Bitmap> {
        private Exception exception;

        @Override
        protected Bitmap doInBackground(String... urls) {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urls[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                return BitmapFactory.decodeStream(connection.getInputStream());
            } catch (Exception e) {
                exception = e;
                return null;
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            Context context = weakContext.get();
            if (context == null) return;

            if (bitmap != null) {
                // 自动设置到ImageView的模式
                ImageView imageView = weakImageView.get();
                if (imageView != null) {
                    imageView.setImageBitmap(bitmap);
                }

                // 回调模式
                if (callback != null) {
                    callback.onSuccess(bitmap);
                }
            } else {
                String errorMsg = exception != null ?
                        exception.getMessage() : "图片下载失败";

                // 自动显示Toast
                Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();

                // 回调模式
                if (callback != null) {
                    callback.onFailure(errorMsg);
                }
            }
        }
    }
}
